package cn.kimming.wms.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.kimming.wms.dao.IChartDAO;
import cn.kimming.wms.domain.OrderGroupType;
import cn.kimming.wms.domain.SaleGroupType;
import cn.kimming.wms.query.OrderChartQueryObject;
import cn.kimming.wms.query.QueryObject;
import cn.kimming.wms.query.SaleChartQueryObject;
import cn.kimming.wms.vo.OrderChartVO;
import cn.kimming.wms.vo.SaleChartVO;

@Repository("chartDAO")
public class ChartDAOImpl implements IChartDAO{

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public List<OrderChartVO> queryOrderChart(OrderChartQueryObject qo) {
		OrderGroupType ogt = OrderGroupType.valueOf(qo.getOrderGroupType());
		Session session = sessionFactory.getCurrentSession();
		StringBuilder hql = new StringBuilder(80);
		hql.append("select new OrderChartVO(");
		hql.append(ogt.getGroupField());
		hql.append(",sum(obj.number),sum(obj.amount)) from OrderBillItem obj");
		hql.append(qo.getQuery());
		hql.append(" group by ");
		hql.append(ogt.getGroupBy());
		Query query = session.createQuery(hql.toString());
		setPlaceHolder(query, qo);
		return query.list();
	}
	
	private void setPlaceHolder(Query query, QueryObject qo) {
		for (int i = 0; i < qo.getParams().size(); i++) {
			query.setParameter(i, qo.getParams().get(i));
		}
	}

	@Override
	public List<SaleChartVO> querySaleChart(SaleChartQueryObject qo) {
		SaleGroupType sgt = SaleGroupType.valueOf(qo.getSaleGroupType());
		Session session = sessionFactory.getCurrentSession();
		StringBuilder hql = new StringBuilder(80);
		hql.append("select new SaleChartVO(");
		hql.append(sgt.getGroupField());
		hql.append(",sum(obj.number),sum(obj.saleAmount),sum(obj.saleAmount - obj.costAmount)) from SaleAccount obj");
		hql.append(qo.getQuery());
		hql.append(" group by ");
		hql.append(sgt.getGroupBy());
		Query query = session.createQuery(hql.toString());
		setPlaceHolder(query, qo);
		return query.list();
	}
	
}
